//
//  LoginController1.m
//  GBKHouse
//
//  Created by XMYY-19 on 2017/8/30.
//  Copyright © 2017年 XMYY-19. All rights reserved.
//

#import "LoginController1.h"
#import "Masonry.h"
#import "Global1.h"
#import "GKBNavigationBar.h"
#import "WebServices.h"
#import "SystemSettting.h"
#import "userNameField.h"
#import "ZXTextField.h"
#import "MyTextField.h"
#import "GBKTabController.h"

static NSString *sessionID = @"";
LoginType loginType;
NSString *currentUser = nil;
@interface LoginController1 ()<UITextFieldDelegate>
@property (nonatomic,strong) ZXTextField *accountModel;
@property (nonatomic,strong) MyTextField *accountPwd;
@end

@implementation LoginController1

{
     NSString *sessionIds;
}

+ (void)setLoginType:(LoginType)type
{
    loginType = type;
}
+ (LoginType)loginType
{
    return loginType;
}
+ (void)setCurrentUser:(NSString *)user
{
    if (currentUser) {
        [currentUser release];
    }
    currentUser = [user retain];
}
+ (NSString *)currentUser
{
    return currentUser;
}
+ (void)setSessionID:(NSString *)sessionId
{
    sessionID = [sessionId retain];
}
+ (NSString *)sessionID
{
    return sessionID;
}
+ (void)setSystem:(id)value key:(NSString*)key
{
    [[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
}
+ (void)setName:(NSString*)name password:(NSString*)passwd
{
    [[NSUserDefaults standardUserDefaults] setObject:name forKey:@"name"];
    [[NSUserDefaults standardUserDefaults] setObject:passwd forKey:@"passwd"];
}
+ (NSString *)userName
{
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"name"];
}
+ (NSString *)passwd
{
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"passwd"];
}

+ (void)setRememberName:(BOOL)remember
{
    [[NSUserDefaults standardUserDefaults] setBool:remember forKey:@"remember"];
}
+ (BOOL )remember
{
    return [[NSUserDefaults standardUserDefaults] boolForKey:@"remember"];
}

+ (void)setAutoLogin:(BOOL)autoLogin
{
    [[NSUserDefaults standardUserDefaults] setBool:autoLogin forKey:@"autoLogin"];
}

+ (BOOL )autoLogin
{
    return [[NSUserDefaults standardUserDefaults] boolForKey:@"autoLogin"];
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"denglubg"]];
    [self initUI];
}
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    [self.userName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(20);
        make.right.equalTo(self.view).with.offset(-20);
        make.top.equalTo(self.logonImage.mas_bottom).with.offset(50);
        make.height.mas_equalTo(40);
    }];
    
}
/**
 初始化UI
 */
-(void)initUI
{
    __block CGFloat textFieldLeft;
    __block CGFloat textFieldWidth;
    __block CGFloat logoTop;
    if (IS_IPAD) {
        logoTop = 83;
        textFieldWidth = SCREEN_WIDTH/2;
        textFieldLeft = (SCREEN_WIDTH-textFieldWidth)/2;
    } else {
        logoTop = 50;
        textFieldLeft = 30;
        textFieldWidth = SCREEN_WIDTH-textFieldLeft*2;
    }
    self.logonImage =[UIButton buttonWithType:UIButtonTypeCustom];
    //[self.logonImage setTitle:@"Smart Home" forState:UIControlStateNormal];
    [self.logonImage setTintColor:[UIColor whiteColor]];
    [self.logonImage setBackgroundImage:[UIImage imageNamed:@"logokuan"] forState:UIControlStateNormal];
    [self.view addSubview:self.logonImage];
    [self.logonImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(90, 90));
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view.mas_top).offset(logoTop);
    }];
    
    CGRect accountF = CGRectMake(textFieldLeft, self.logonImage.bottom+170, textFieldWidth, 40);
    ZXTextField *accountModel = [[ZXTextField alloc]initWithFrame:accountF withIcon:@"zhanghao" withPlaceholderText:@"用户名或邮箱"];
    accountModel.inputText.autocapitalizationType = UITextAutocapitalizationTypeNone;
    accountModel.inputText.autocorrectionType = UITextAutocorrectionTypeNo;
    accountModel.inputText.keyboardType = UIKeyboardTypeASCIICapable;
    accountModel.frame = accountF;
    accountModel.inputText.delegate = self;
    [self.view addSubview:accountModel];
    self.accountModel = accountModel;
    [self.accountModel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(textFieldLeft);
        make.right.mas_equalTo(-textFieldLeft);
        make.top.equalTo(self.logonImage.mas_bottom).with.offset(30);
        make.height.mas_equalTo(40);

    }];
    
    CGRect accountF1 = CGRectMake(textFieldLeft, self.accountModel.bottom+170, textFieldWidth, 40);
    MyTextField *accountPwd = [[MyTextField alloc]initWithFrame:accountF1 withIcon:@"mima" withPlaceholderText:@"密码"];
    accountPwd.inputText.autocapitalizationType = UITextAutocapitalizationTypeNone;
    accountPwd.inputText.autocorrectionType = UITextAutocorrectionTypeNo;
    accountPwd.inputText.keyboardType = UIKeyboardTypeASCIICapable;
    accountPwd.frame = accountF;
    accountPwd.inputText.delegate = self;
    [self.view addSubview:accountPwd];
    self.accountPwd = accountPwd;
    
    [accountPwd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(textFieldLeft);
        make.right.mas_equalTo(-textFieldLeft);
        make.top.equalTo(accountModel.mas_bottom).with.offset(10);
        make.height.mas_equalTo(40);
    }];
    
    self.ForgotPwdBtn  =[[UIButton alloc] init];
    [self.ForgotPwdBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
    [self.ForgotPwdBtn setTitleColor:[UIColor colorWithRGBColorByString:@"#86a0b4"] forState:UIControlStateNormal];
        [self.ForgotPwdBtn addTarget:self action:@selector(regist) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.ForgotPwdBtn];
    self.ForgotPwdBtn.hidden = YES;
    
    [self.ForgotPwdBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(100);
        make.right.equalTo(self.view).with.offset(-100);
        make.top.equalTo(accountPwd.mas_bottom).with.offset(4);
        make.height.mas_equalTo(40);
    }];
    
    self.loginBtn  =[[UIButton alloc] init];
    [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [self.loginBtn setTitleColor:[UIColor colorWithRGBColorByString:@"#c2e6f9"] forState:UIControlStateNormal];
    //[self.loginBtn setBackgroundColor:[UIColor purpleColor]];
    self.loginBtn.layer.cornerRadius = 8;
    self.loginBtn.layer.borderColor = [UIColor colorWithRGBColorByString:@"#7ecef4"].CGColor;
    [self.loginBtn.layer setBorderWidth:1];
    [self.view addSubview:self.loginBtn];
    [self.loginBtn addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(textFieldLeft);
        make.right.mas_equalTo(-textFieldLeft);
        make.top.equalTo(self.ForgotPwdBtn.mas_bottom).with.offset(4);
        make.height.mas_equalTo(40);
    }];
    
    
    self.regeBtn  =[[UIButton alloc] init];
    self.regeBtn.font =[UIFont systemFontOfSize:18];
    [self.regeBtn setTitle:@"注册" forState:UIControlStateNormal];
    [self.regeBtn setTitleColor:[UIColor colorWithRGBColorByString:@"#c2e6f9"] forState:UIControlStateNormal];
    //[self.loginBtn setBackgroundColor:[UIColor purpleColor]];
    self.regeBtn.layer.cornerRadius = 8;
    self.regeBtn.layer.borderColor = [UIColor colorWithRGBColorByString:@"#7ecef4"].CGColor;
    [self.regeBtn.layer setBorderWidth:1];
    [self.view addSubview:self.regeBtn];
    [self.regeBtn addTarget:self action:@selector(regist) forControlEvents:UIControlEventTouchUpInside];
    self.regeBtn.hidden = YES;
    
    [self.regeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(textFieldLeft);
        make.right.mas_equalTo(-textFieldLeft);
        make.top.equalTo(self.loginBtn.mas_bottom).with.offset(8);
        make.height.mas_equalTo(40);
    }];

    self.gusetBtn  =[[UIButton alloc] init];
    [self.gusetBtn setTitle:@"体验模式" forState:UIControlStateNormal];
    [self.gusetBtn setTitleColor:[UIColor colorWithRGBColorByString:@"#86a0b4"] forState:UIControlStateNormal];
        [self.gusetBtn addTarget:self action:@selector(regist) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.gusetBtn];
    self.gusetBtn.hidden = YES;
    
    [self.gusetBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(100);
        make.right.equalTo(self.view).with.offset(-100);
        make.top.equalTo(self.regeBtn.mas_bottom).with.offset(8);
        make.height.mas_equalTo(40);
    }];
    
    //收键盘
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];
    [self.view addGestureRecognizer:singleTap];
    
}

//收键盘
-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer{
    
    [self.accountModel.inputText resignFirstResponder];
    CGPoint center = [UIApplication sharedApplication].keyWindow.center;
    self.view.center = center;
    
}

-(void)regist{
    
    NSString *nameError = NSLocalizedString(@"功能开发中", nil);
    [iToast showTip:nameError gravity:iToastGravityCenter];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    if ([LoginController1 autoLogin]) {
        [self.view setHidden:NO];
        self.willAutoLogin = YES;
        [self login];
        [self openMain];
    }
    else
    {
        self.willAutoLogin = NO;
        [self.view setHidden:NO];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//{
//    // Return YES for supported orientations
//    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
//}


- (void)ping
{
    
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId];
    [WebServices requestStartOrder:@"ping" body:body target:self action:@selector(pingEnd:) errorTip:nil];
}
- (void)pingEnd:(NSDictionary *)dic
{
    
    NSString *result = [dic objectForKey:@"result"];
    NSString *state = [dic objectForKey:@"state"];
    if ([result isEqualToString:@"0"])
    {
        if ([state isEqualToString:@"online"])
        {
            [[NSUserDefaults standardUserDefaults] setObject:sessionIds forKey:@"sessionIds"];
         if (self.willAutoLogin == NO)
            {//手动登录，弹出main(自动登录已弹出main)
                [self openMain];
            }
            //自动登录
            else
            {
                  // [[GKBMainController mainCtr]loadList];
                [self.navigationController pushViewController:[GBKTabController new] animated:YES];
            }
            return;
        }
    }
    
    if (self.willAutoLogin == YES)
    {
        self.view.hidden = NO;
        [LoginController1 setAutoLogin:NO];
        [[GKBMainController mainCtr] dismissView];
    }
    
    //主机不在线情况
    NSString *errorTip = NSLocalizedString(@"Host is not online!", nil);
    [iToast showTip:errorTip gravity:iToastGravityCenter];
    //    [self login];
}

- (void)loginEnd:(NSDictionary *)dic
{
    
    NSLog(@"%@", dic);
    NSString *result = [dic objectForKey:@"result"];
    NSString *sessionId = [dic objectForKey:@"sessionId"];
    [[NSUserDefaults standardUserDefaults] setObject:[dic objectForKey:@"hostnum"] forKey:@"hostnum"];
    NSLog(@"%@,%@", result, sessionId);
    if ([result isEqualToString:@"0"]) {
        [LoginController1 setSessionID:sessionId];
        NSString *userName = [LoginController1 currentUser];
        sessionIds = sessionId;
        [AppFile saveSuccessLoginUser:userName];//保存成功登录用户名到文件
        self.accountPwd.inputText.text = @"";
        self.accountModel.inputText.text = @"";
        [self ping];
        
    }
    else
    {
        NSString *loginError = NSLocalizedString(@"Login fail!Fill in the correct information!", nil);
        [iToast showTip:loginError gravity:iToastGravityCenter];
        
        self.view.hidden = NO;
        [LoginController1 setAutoLogin:NO];
        [[GKBMainController mainCtr] dismissView];
    }
    
}

- (void)login
{
    
    NSString *name = self.accountModel.inputText.text;
    NSString *passwd = self.accountPwd.inputText.text;
//    NSString *name = @"88";
//    NSString *passwd = @"88";
    NSLog(@"name = %@, passwd = %@",name,passwd);
    [LoginController1 setCurrentUser:name];
    if ([name length] <1 || [passwd length] < 1) {
        
        NSString *nameError = NSLocalizedString(@"用户名或密码不能为空", nil);
        [iToast showTip:nameError gravity:iToastGravityCenter];
        
        return;//输入信息不完整
        
    }
    [self.accountPwd.inputText resignFirstResponder];
//    if ([passwd length]<1)
//    {
//        NSString *passwdError = NSLocalizedString(@"密码", nil);
//        [iToast showTip:passwdError gravity:iToastGravityCenter];
//        return;//输入信息不完整
//    }
    //[LoginController1 setLoginType:LoginTypeFar];//设置登录模式
//    if (check.selected) {
//        [LoginController1 setRememberName:YES];
//        [LoginController1 setAutoLogin:YES];
//        [LoginController1 setName:name password:passwd];
//    }
//    else
//    {
//        [LoginController1 setRememberName:NO];
//        [LoginController1 setAutoLogin:NO];
//    }
    
    //     NSString *json = @"[{\"username\":\"wstest\", \"userpassword\":\"t123\"}]";
    NSString *fomate = @"[{\"username\":\"%@\", \"userpassword\":\"%@\"}]";
    NSString *json = [NSString stringWithFormat:fomate, name, passwd];
    NSString *order = @"login";
    NSString *loginError = NSLocalizedString(@"LoginFail", nil);
    NSString *errorType = [OperationTip errorType:ErrorTypeNetworkFail];
    NSString *errorTip = [NSString stringWithFormat:@"%@, %@", loginError, errorType];
    [WebServices setShowConnectting:YES];
    [WebServices requestStartOrder:order body:json target:self action:@selector(loginEnd:) errorTip:errorTip];
    //   [WebServices requestLogin:json target:self action:@selector(loginEnd:) errorTip:@"loginError"];
    //    [self startLogin];
    //   [self openMain];
}
- (IBAction)localLogin
{
//    return;
//    BOOL equsFile = NO;
//    NSString *saveEqusFile = [AppFile documentsPath:@"euqs.bat"];
//    equsFile = [AppFile is_file_exsit:saveEqusFile];
//    if (equsFile) {
//        [LoginController1 setLoginType:LoginTypeLocal];//设置登录模式
//        NSString *localUser = [SystemSettting localUserName];
//        if (localUser) {
//            [LoginController1 setCurrentUser:localUser];
//        }
//        else
//        {
//            [LoginController1 setCurrentUser:nil];
//        }
//        
//        [self openMain];
//    }
//    else
//    {
//        NSString *errorTip = NSLocalizedString(@"Fail Never far login!", nil);
//        [iToast showTip:errorTip gravity:iToastGravityBottom];
//    }
    
}
- (void)openMain
{
    
   GBKTabController *controller =[[GBKTabController alloc] init];
    //GKBMainController *controller = [[GKBMainController alloc]initWithNibName:@"GKBMainController" bundle:nil];
    if ([UIDevice currentDevice].systemVersion.floatValue <= 6.0) {
        [self presentModalViewController:controller animated:NO];
    }
    else
    {
        [self presentViewController:controller animated:NO completion:nil];
    }
    [controller release];
}
- (void)checkAction
{
//    if (!check.selected) {
//        [check setImage:[UIImage imageNamed:@"check.png"] forState:UIControlStateNormal];
//        check.selected = YES;
//    }
//    else
//    {
//        [check setImage:[UIImage imageNamed:@"uncheck.png"] forState:UIControlStateNormal];
//        check.selected = NO;
//    }
}

- (void)systemMenu
{
    SystemSettting *systemSetting = [[SystemSettting alloc]init];
    [self presentModalViewController:systemSetting animated:NO];
    [systemSetting release];
}

- (NSString *)buildVersion
{
    NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    
    return build;
}

#pragma mark - UITextfieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSLog(@"%f,%f",self.view.center.x, self.view.center.y);
    CGPoint center = [UIApplication sharedApplication].keyWindow.center;
    
    if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
        center.y = center.y - 70;
    }
    else
    {
        center.x = center.x + 70;
    }
    
    self.view.center = center;
    //    self.view.center = CGPointMake(230, 240);
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    CGPoint center = [UIApplication sharedApplication].keyWindow.center;
    self.view.center = center;
    //    self.view.center = CGPointMake(160, 240);
    return YES;
}

@end
